package com.example.aiinterview.config;

import com.example.aiinterview.model.User;
import com.example.aiinterview.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 应用安全配置类
 * 配置URL访问权限、登录/登出行为及CSRF策略。
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final UserService userService;

    @Bean
    public UserDetailsService userDetailsService() {
        return username -> {
            User user = userService.findByUsername(username);
            if (user == null) {
                throw new UsernameNotFoundException("用户不存在: " + username);
            }
            return user;
        };
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(auth -> auth
                        // 静态资源和认证端点允许匿名访问
                        .requestMatchers("/", "/register", "/login", "/css/**", "/js/**", "/webjars/**").permitAll()
                        // 管理员接口需要ADMIN角色
                        .requestMatchers("/admin/**").hasRole("ADMIN")
                        // 受保护的资源需要认证
                        .requestMatchers("/interview/**", "/result/**", "/interviews").authenticated()
                        // 其他所有请求都需要认证
                        .anyRequest().authenticated()
                )
                .formLogin(form -> form
                        .loginPage("/login")
                        .defaultSuccessUrl("/interview", true) // 强制重定向到成功页面
                        .permitAll()
                )
                .logout(logout -> logout
                        .logoutSuccessUrl("/login?logout") // 登出后跳转登录页并带参数
                        .permitAll()
                )
                // 禁用CSRF防护（主要供API测试用，生产环境应谨慎评估）
                .csrf(csrf -> csrf.disable());

        return http.build();
    }
}